import { AudioSource, Node, _decorator, director, AudioClip, resources } from 'cc'
// const { uniquelyReferenced } = _decorator

// @uniquelyReferenced
export class AudioManager {
  private _audioSource: AudioSource;

  constructor() {
    // const audioNode = new Node()
    // audioNode.name = '__audioNode__'

    // director.getScene().addChild(audioNode)
    // director.addPersistRootNode(audioNode)
    // this._audioSource = audioNode.addComponent(AudioSource)
  }

  public get audioSource() {
    return this._audioSource
  }

  playOneShot(clip: AudioClip | string, volume: number = 1.0) {
      if(clip instanceof AudioClip) {
        this._audioSource.playOneShot(clip, volume)
      } else {
        resources.load(clip, AudioClip, (err, audio) => {
          if(err) {

          }

          this._audioSource.playOneShot(audio, volume)
        })
      }
  }

  /**
     * @en
     * play long audio, such as the bg music
     * @zh
     * 播放长音频，比如 背景音乐
     * @param sound clip or url for the sound
     * @param volume
     */
    play(sound: AudioClip | string, volume: number = 1.0) {
        if (sound instanceof AudioClip) {
            this._audioSource.stop();
            this._audioSource.clip = sound;
            this._audioSource.play();
            this.audioSource.volume = volume;
        }
        else {
            resources.load(sound, (err, clip: AudioClip) => {
                if (err) {
                    console.log(err);
                }
                else {
                    this._audioSource.stop();
                    this._audioSource.clip = clip;
                    this._audioSource.play();
                    this.audioSource.volume = volume;
                }
            });
        }
    }

    /**
     * stop the audio play
     */
    stop() {
        this._audioSource.stop();
    }

    /**
     * pause the audio play
     */
    pause() {
        this._audioSource.pause();
    }

    /**
     * resume the audio play
     */
    resume(){
        this._audioSource.play();
    }
}

export const audioManager = new AudioManager()
